package server.mapper;

import server.HttpServlet;
import server.UrlUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xingyi
 */
public class Host {
    private Map<String, Context> contextMap = new HashMap<>();
    private String name;
    private String appBase;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAppBase() {
        return appBase;
    }

    public void setAppBase(String appBase) {
        this.appBase = appBase;
    }

    public void addContext(Context context) {
        contextMap.put(context.getContextPath(), context);
    }

    public Context getContext(String contextPath) {
        return contextMap.get(contextPath);
    }


    public HttpServlet getServlet(String url) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        String[] parts = UrlUtils.splitUrl(url);
        String contextPath = parts[0];
        String path = parts[1];
        Context context = getContext(contextPath);
        if (context == null) {
            return null;
        }
        return context.getServlet(path);
    }
}
